<?php

namespace app\index\controller;

use Db;
use EasyWeChat\Factory;

//use wechat\Pay as wxPay;

class Pay extends Base
{

    public function wxPayConfig()
    {

        $config = [
            // 必要配置
            'app_id' => config('wechat.AppId'),
            'mch_id' => config('wechat.MchId'),
            'key' => config('wechat.ApiKey'),   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
//            'cert_path'          => '', // XXX: 绝对路径！！！！
//            'key_path'           => '',      // XXX: 绝对路径！！！！
            'notify_url' => request()->domain() . '/index/Notify/wxPayNotify',     // 你也可以在下单时单独设置来想覆盖它
        ];
        return Factory::payment($config);
    }


    //购买会员
    public function payLevel()
    {

        $id = input('level');
        if (!$id) {
            return ['code' => 0, 'msg' => '未知会员'];
        }

        //会员等级信息
        $info = Db::name('user_level')->field('price,level_name')->where('id', $id)->find();

        if (!$info) {
            return ['code' => 0, 'msg' => '会员等级不存在'];
        }

        $order_sn = create_order_sn();  //自定义订单号

        $wx = isWeixin();
        $pay_type = input('pay_type');

        if ($wx || $pay_type==1) {  //微信支付 预订单

            $time = time();
            $orderData = [
                'body' => '充值会员',
                'out_trade_no' => $order_sn,
//                'total_fee' => 1,
                'total_fee' => $info['price'] * 100,
//            'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => request()->domain() . '/index/Notify/wxPayNotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $this->userInfo['wx_openid'],
                'sign_type' => 'MD5',
                'timeStamp' => $time
            ];

            if ($pay_type == 1) {
                $orderData['openid']='';
                $orderData['trade_type'] = 'MWEB';
                $orderData['scene_info'] = json_encode(['h5_info' => ['type' => 'Wap', 'wap_url' => request()->url(true), 'wap_name' => '充值会员']]);

            }

            if ($orderData['openid'] == 'oSSrBwSQGXtpRX9bBDWMJhw6EzA8' || $orderData['openid'] == 'oSSrBwQqaWK01hGZolJ1pCEEZj5Y' ) {

                $orderData['total_fee'] = 1;
            }

            $app = $this->wxPayConfig();

            $res = $app->order->unify($orderData);

//            if(!empty($res['return_code']) && !empty($res['result_code']) && $res['return_code']=='SUCCESS' && $res['result_code']=='SUCCESS' ){
            if (!empty($res['prepay_id'])) {

                $add = $this->createOrder($id,$order_sn,$info['price'],$info['level_name']);

                if ($add) {

                    if ($pay_type == 1) {
                        //其他浏览器支付
                        return ['code' => 1, 'msg' => 'success', 'pay_url' => $res['mweb_url']];
                    }

                    $jssdk = $app->jssdk;

                    $json = $jssdk->sdkConfig($res['prepay_id']);
                    $json['timeStamp'] = $json['timestamp'];
                    unset($json['timestamp']);
//                    $res['time'] = $time;
//                    $res['total_fee'] = $orderData['total_fee'];
                    return ['code' => 1, 'msg' => 'success', 'data' => $json, 'phone' => $this->userInfo['phone'] ?: ''];

                } else {

                    return ['code' => 0, 'msg' => '创建订单失败'];

                }
            } else {

                return ['code' => 0, 'msg' => '创建订单失败', 'res' => $res];

            }
        }else{
            //支付宝支付
//            include_once '../vendor/alipay/config.php';
            include_once '../vendor/alipay/wappay/service/AlipayTradeService.php';
            include_once '../vendor/alipay/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php';

            //商户订单号，商户网站订单系统中唯一订单号，必填
            $out_trade_no = $order_sn;

            //订单名称，必填
            $subject = $info['level_name'];

            //付款金额，必填
            $total_amount = $info['price'];

            if($this->uid==931){
                $total_amount = 0.01;
            }
            $config = config('alipay.');

            if($lesson_id=input('lesson_id')){
                $config['return_url'] = request()->domain().url('pay/order',['lesson_id'=>$lesson_id]);
            }else{
                $config['return_url'] = request()->domain().url('mine/level');
            }

            //商品描述，可空
            $body = '充值会员共'.$total_amount.'元';

            $aop = new \AlipayTradeService($config);

            //构造参数
            $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
            $payRequestBuilder->setBody($body);
            $payRequestBuilder->setSubject($subject);
            $payRequestBuilder->setTotalAmount($total_amount);
            $payRequestBuilder->setOutTradeNo($out_trade_no);



            /**
             * pagePay 电脑网站支付请求
             * @param $builder 业务参数，使用buildmodel中的对象生成。
             * @param $return_url 同步跳转地址，公网可以访问
             * @param $notify_url 异步通知地址，公网可以访问
             * @return $response 支付宝返回的信息
             */

            $add = $this->createOrder($id,$order_sn,$info['price'],$info['level_name']);

            if($add){

                $response = $aop->wapPay($payRequestBuilder, $config['return_url'], $config['notify_url']);

                //输出表单
                return $response;
            }else{
                $this->error('创建订单失败');
            }
        }

        //支付宝支付

    }

    //购买渠道会员
    public function paySalesLevel()
    {

        $id = input('level');
        if (!$id) {
            return ['code' => 0, 'msg' => '未知会员'];
        }

        //会员等级信息
        $info = Db::name('user_sales')->field('price,sales_name')->where('id', $id)->find();

        if (!$info) {
            return ['code' => 0, 'msg' => '渠道等级不存在'];
        }

        $order_sn = create_order_sn();  //自定义订单号

        $wx = isWeixin();
        $pay_type = input('pay_type');

        if ($wx || $pay_type==1) {  //微信支付 预订单

            $time = time();
            $orderData = [
                'body' => '充值会员',
                'out_trade_no' => $order_sn,
//                'total_fee' => 1,
                'total_fee' => $info['price'] * 100,
//            'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => request()->domain() . '/index/Notify/wxPayNotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $this->userInfo['wx_openid'],
                'sign_type' => 'MD5',
                'timeStamp' => $time
            ];

            if ($pay_type == 1) {
                $orderData['openid']='';
                $orderData['trade_type'] = 'MWEB';
                $orderData['scene_info'] = json_encode(['h5_info' => ['type' => 'Wap', 'wap_url' => request()->url(true), 'wap_name' => '充值会员']]);

            }

            if ($orderData['openid'] == 'oSSrBwSQGXtpRX9bBDWMJhw6EzA8' || $orderData['openid'] == 'olijd5pTHftLkOl1MGlLVHNeGS1A' ) {

                $orderData['total_fee'] = 1;
            }

            $app = $this->wxPayConfig();

            $res = $app->order->unify($orderData);

//            if(!empty($res['return_code']) && !empty($res['result_code']) && $res['return_code']=='SUCCESS' && $res['result_code']=='SUCCESS' ){
            if (!empty($res['prepay_id'])) {

                $add = $this->createOrder($id,$order_sn,$info['price'],$info['sales_name'],2);

                if ($add) {

                    if ($pay_type == 1) {
                        //其他浏览器支付
                        return ['code' => 1, 'msg' => 'success', 'pay_url' => $res['mweb_url']];
                    }

                    $jssdk = $app->jssdk;

                    $json = $jssdk->sdkConfig($res['prepay_id']);
                    $json['timeStamp'] = $json['timestamp'];
                    unset($json['timestamp']);
//                    $res['time'] = $time;
//                    $res['total_fee'] = $orderData['total_fee'];
                    return ['code' => 1, 'msg' => 'success', 'data' => $json, 'phone' => $this->userInfo['phone'] ?: ''];

                } else {

                    return ['code' => 0, 'msg' => '创建订单失败'];

                }
            } else {

                return ['code' => 0, 'msg' => '创建订单失败', 'res' => $res];

            }
        }else{
            //支付宝支付
//            include_once '../vendor/alipay/config.php';
            include_once '../vendor/alipay/wappay/service/AlipayTradeService.php';
            include_once '../vendor/alipay/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php';

            //商户订单号，商户网站订单系统中唯一订单号，必填
            $out_trade_no = $order_sn;

            //订单名称，必填
            $subject = $info['level_name'];

            //付款金额，必填
            $total_amount = $info['price'];

            if($this->uid==931){
                $total_amount = 0.01;
            }
            $config = config('alipay.');

            if($lesson_id=input('lesson_id')){
                $config['return_url'] = request()->domain().url('pay/order',['lesson_id'=>$lesson_id]);
            }else{
                $config['return_url'] = request()->domain().url('mine/level');
            }

            //商品描述，可空
            $body = '充值会员共'.$total_amount.'元';

            $aop = new \AlipayTradeService($config);

            //构造参数
            $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
            $payRequestBuilder->setBody($body);
            $payRequestBuilder->setSubject($subject);
            $payRequestBuilder->setTotalAmount($total_amount);
            $payRequestBuilder->setOutTradeNo($out_trade_no);



            /**
             * pagePay 电脑网站支付请求
             * @param $builder 业务参数，使用buildmodel中的对象生成。
             * @param $return_url 同步跳转地址，公网可以访问
             * @param $notify_url 异步通知地址，公网可以访问
             * @return $response 支付宝返回的信息
             */

            $add = $this->createOrder($id,$order_sn,$info['price'],$info['level_name']);

            if($add){

                $response = $aop->wapPay($payRequestBuilder, $config['return_url'], $config['notify_url']);

                //输出表单
                return $response;
            }else{
                $this->error('创建订单失败');
            }
        }

        //支付宝支付

    }

    //订单确认页
    public function order()
    {

        $id = input('lesson_id');

        if (!$id) {
            $this->error('未知课程');
        }


//        $res = Db::name('order')->where(['type'=>2,'other_id'=>$id,'status'=>1,'uid'=>$this->uid])->find();
//
//        //支付过无需再支付
//        if($res || $this->userInfo['level_validity']>time()){
//
//            $section_id = Db::name('lesson_section')->where('lesson_id',$id)->order('rank asc')->value('id');
//
//
//            $this->redirect(url("section/play").'?section_id='.$section_id);
//        }

        //课程详情
        $lesson = Db::name('lesson')->where('id', $id)->find();

        if (!$lesson) {
            $this->error('课程不存在');
        }

        //推荐会员
        if ($this->userInfo['level'] == 0) {

            $vip = Db::name('user_level')->order('price asc')->find();

            $this->assign('vip', $vip);
        }

        $this->assign('lesson', $lesson);
        $this->assign('user', $this->userInfo);
        $this->assign('order_sn', create_order_sn());
        $this->assign('img_path', config('api.oss_img_path'));

        return $this->fetch('lesson/order');
    }

    //订单确认页
    public function order2()
    {

        $id = input('lesson_id');

        if (!$id) {
            $this->error('未知课程');
        }

        //课程详情
        $lesson = Db::name('lesson')->where('id', $id)->find();

        if (!$lesson) {
            $this->error('课程不存在');
        }

        //推荐会员
        if ($this->userInfo['level'] == 0) {

            $vip = Db::name('user_level')->order('price asc')->find();

            $this->assign('vip', $vip);
        }

        $this->assign('lesson', $lesson);
        $this->assign('user', $this->userInfo);
        $this->assign('order_sn', create_order_sn());
        $this->assign('img_path', config('api.oss_img_path'));

        return $this->fetch('lesson/order2');
    }

    //购买课程
    public function payLesson()
    {

        $id = input('lesson_id');
        if (!$id) {
            return ['code' => 0, 'msg' => '未知课程'];
        }

        //课程信息
        $info = Db::name('lesson')->field('price,lesson_name')->where('id', $id)->find();

        if (!$info) {
            return ['code' => 0, 'msg' => '课程不存在'];

        }

        $order_sn = create_order_sn();  //自定义订单号

        $wx = isWeixin();

        $pay_type = input('pay_type');
        if ($wx || $pay_type == 1) {  //微信支付 预订单

            $time = time();
            $orderData = [
                'body' => '购买课程',
                'out_trade_no' => $order_sn,
//                'total_fee' => 1,
                'total_fee' => $info['price'] * 100,
//            'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                'notify_url' => request()->domain() . '/index/Notify/wxPayNotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $this->userInfo['wx_openid'],
                'sign_type' => 'MD5',
                'timeStamp' => $time
            ];
            if ($pay_type == 1) {
                $orderData['openid']='';
                $orderData['trade_type'] = 'MWEB';
                $orderData['scene_info'] = json_encode(['h5_info' => ['type' => 'Wap', 'wap_url' => request()->url(true), 'wap_name' => '购买课程']]);

            }

            if ($orderData['openid'] == 'olijd5tPxT0z-xby9yajc1_sfYUI' || $orderData['openid'] == 'olijd5pTHftLkOl1MGlLVHNeGS1A' || $this->uid==931) {

                $orderData['total_fee'] = 1;
            }


            $app = $this->wxPayConfig();

            $res = $app->order->unify($orderData);

//            if(!empty($res['return_code']) && !empty($res['result_code']) && $res['return_code']=='SUCCESS' && $res['result_code']=='SUCCESS' ){
            if (!empty($res['prepay_id'])) {

                $add = $this->createOrder($id,$order_sn,$info['price'],$info['lesson_name'],2);

                if ($add) {

                    if ($pay_type == 1) {
                        //其他浏览器支付
                        return ['code' => 1, 'msg' => 'success', 'pay_url' => $res['mweb_url']];
                    }

                    $jssdk = $app->jssdk;

                    $json = $jssdk->sdkConfig($res['prepay_id']);
                    $json['timeStamp'] = $json['timestamp'];
                    unset($json['timestamp']);
//                    $res['time'] = $time;
//                    $res['total_fee'] = $orderData['total_fee'];

                    //固定菜单的课程 支付成功后播放第一章节
                    $menu_id = DB::name('config')
                        ->where('key', 'bottom_menu')
                        ->value('value');

                    if ($menu_id == $id) {

                        $section_id = Db::name('lesson_section')->where(['lesson_id' => $id, 'status' => 1, 'rank' => 1])->value('id');
                    } else {
                        $section_id = 0;
                    }


                    return ['code' => 1, 'msg' => 'success', 'data' => $json, 'phone' => $this->userInfo['phone'] ?: '', 'section_id' => $section_id];

                } else {

                    return ['code' => 0, 'msg' => '创建订单失败'];
                }
            } else {

                return ['code' => 0, 'msg' => '创建订单失败', 'res' => $res];

            }
        } else {
            //支付宝支付
//            include_once '../vendor/alipay/config.php';
            include_once '../vendor/alipay/wappay/service/AlipayTradeService.php';
            include_once '../vendor/alipay/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php';

            //商户订单号，商户网站订单系统中唯一订单号，必填
            $out_trade_no = $order_sn;

            //订单名称，必填
            $subject = $info['lesson_name'];

            //付款金额，必填
            $total_amount = $info['price'];

            if($this->uid==931){
                $total_amount = 0.01;
            }

            //商品描述，可空
            $body = '购买课程共'.$total_amount.'元';

            $config = config('alipay.');

            $config['return_url'] = request()->domain().url('pay/order',['lesson_id'=>$id]);
//            echo $config['return_url'];exit;
            //构造参数
            $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
            $payRequestBuilder->setBody($body);
            $payRequestBuilder->setSubject($subject);
            $payRequestBuilder->setTotalAmount($total_amount);
            $payRequestBuilder->setOutTradeNo($out_trade_no);
            $payRequestBuilder->setTimeExpress('1m');

            /**
             * pagePay 电脑网站支付请求
             * @param $builder 业务参数，使用buildmodel中的对象生成。
             * @param $return_url 同步跳转地址，公网可以访问
             * @param $notify_url 异步通知地址，公网可以访问
             * @return $response 支付宝返回的信息
             */


            $add = $this->createOrder($id,$order_sn,$info['price'],$info['lesson_name'],2);

            if($add){
                $aop = new \AlipayTradeService($config);


                $response = $aop->wapPay($payRequestBuilder, $config['return_url'], $config['notify_url']);


                //输出表单
                return $response;
            }else{
                $this->error('创建订单失败');
            }


        }
    }

    public function createOrder($id,$order_sn,$price,$order_name,$type=1){

        //创建订单
        $row = array(
            'uid' => $this->uid,
            'out_trade_no' => $order_sn,
            'total_fee' => $price,
            'pid' => $this->userInfo['pid'],
            'ppid' => $this->userInfo['ppid'],
            'other_id' => $id,
            'type' => $type,
            'status' => 0,
            'order_name' => $order_name,
            'create_time' => time()
        );

        //分佣 直接推荐
        if ($row['pid']) {

            $parent = Db::name('user a')->field('a.sales,b.commission1')
                ->leftJoin('user_sales b', 'a.sales=b.id')
                ->where('a.id=' . $row['pid'])->find();

            if ($parent) {

                if ($parent['sales'] > 0) {
//                    //普通用户10%
//                    $row['commission1'] = round($price * 0.1, 2);
//                } else {
                    //会员分佣
                    $row['commission1'] = round($price * $parent['commission1'] / 100, 2);

                }
            }
        }

        //分佣 间接推荐
        if ($row['ppid']) {

            $top = Db::name('user a')->field('a.sales,b.commission2')
                ->leftJoin('user_sales b', 'a.sales=b.id')
                ->where('a.id=' . $row['ppid'])->find();

            if ($top) {

                if ($top['sales'] > 0) {
                    //只有会员才拥有间接推荐佣金
                    $row['commission2'] = round($price * $top['commission2'] / 100, 2);

                }
            }
        }

        return Db::name('order')->insert($row);
    }


    public function queryOrder()
    {
        $type = input('type');
        $other_id = input('other_id');

        $res = Db::name('order')->where(['type'=>$type,'other_id'=>$other_id,'status'=>1,'uid'=>$this->uid])->find();

        if($type==2 && ($res || ($this->userInfo['level']>0 && $this->userInfo['level_validity']>time()))){
            $section_id = Db::name('lesson_section')->where('lesson_id',$other_id)->order('rank asc')->value('id');
            return ['code'=>1,'section_id'=>$section_id];

        }

        if($res){

            return ['code'=>1];
        }else{
            return ['code'=>0];
        }

    }


}